package com.glsc.ngateway.opmanage.event;

import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.archive.ArchiveClient;
import com.glsc.ngateway.opmanage.event.vo.ArchiveUserSynEvent;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.archive.CounterParty;
import com.glsc.ngateway.opmanage.service.archive.ArchiveService;
import com.glsc.ngateway.opmanage.service.archive.CounterPartyService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


@Component
public class ArchiveUserSynEventListener implements ApplicationListener<ArchiveUserSynEvent> {


    @Resource
    private ArchiveService archiveService;

    @Resource
    private CounterPartyService counterPartyService;


    @Override
    public void onApplicationEvent(ArchiveUserSynEvent event) {
        if (Objects.isNull(event)) {
            return;
        }

        ArchiveClient oldClient = archiveService.findClientById(event.getClientId());
        if (Objects.nonNull(oldClient)) {
            return;
        }

        ArchiveClient client = new ArchiveClient();
        client.setClientName(event.getClientName());
        client.setClientId(event.getClientId());
        client.setClientType(event.getClientType());
        client.setCreateOperatorName("系统创建");

        if (StringUtils.isNotBlank(event.getPartyName())) {
            List<CounterParty> list = counterPartyService.findByCondition(CounterParty.builder().partyName(event.getPartyName()).build());
            if (CollectionUtils.isNotEmpty(list)) {
                client.setPartyId(list.get(0).getId());
            } else {
                CounterParty counterParty = CounterParty.builder().partyName(event.getPartyName()).enableFlag("Y")
                        .partyOrganCode(event.getPartyOrganCode()).createTime(LocalDateTime.now()).build();
                CounterParty save = counterPartyService.save(counterParty);
                client.setPartyId(save.getId());
            }
        }

        ArchiveClient saveArchiveClient = archiveService.saveArchiveClient(client);
        archiveService.createByClientType(saveArchiveClient.getClientId(), null, "系统创建");
    }

}
